package com.ilink.teacherservice.controller;

/**
 * <h3>new-ilink-java-backend</h3>
 *
 * @Description <p>用于为教师端提供资源文件的上传和加工</p>
 * @Author pengshiyao
 * @Date 2024-09-16 13:35
 **/

import com.ilink.ilinkapi.dto.teacher.UploadWebSourceDTO;
import com.ilink.ilinkcommon.domain.PO.studyservice.StudyCourseFile;
import com.ilink.ilinkcommon.domain.PO.studyservice.StudyResourceSort;
import com.ilink.ilinkcommon.domain.PO.studyservice.StudyWebSourse;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.log.method.MethodLog;
import com.ilink.ilinkcommon.utils.SnowflakeIdGenerator;
import com.ilink.teacherservice.mapper.StudyCourseFileMapper;
import com.ilink.teacherservice.mapper.StudyResourceSortMapper;
import com.ilink.teacherservice.service.FileSourceHandleThreadService;
import com.ilink.teacherservice.service.StudyWebSourseService;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @ClassName FileSourceController
 * @Description
 * @Author pengshiyao
 * @Date 2024-09-16 13:35
 **/
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/teacher/handlefileSource")
public class FileSourceController {

    private final FileSourceHandleThreadService fileSourceHandleThreadService;

    private final StudyWebSourseService studyWebSourseService;

    private final StudyCourseFileMapper studyCourseFileMapper;
    private final StudyResourceSortMapper studyResourceSortMapper;

    //音视频上传与加工-并发（最终接口）
    @MethodLog("音视频上传与加工-并发")
    @PostMapping("/handlevideoSource_thread")
    public R handlevideoSourceThread(
        @RequestParam("file") MultipartFile file,
        @RequestParam("courseFileId") Long courseFileId,
        @RequestParam("language") String language,
        @RequestParam("isTranslated") Boolean isTranslated,
        @RequestParam("speakerType") String speakerType,
        @RequestParam("courseId") Long courseid,
        @RequestParam("sortOrder") Integer sortOrder) {
        return fileSourceHandleThreadService.uploadSourceTask(file, courseFileId, language,
            isTranslated, speakerType, courseid, sortOrder);

    }

    //文档上传与加工-并发（最终接口）
    @MethodLog("文档上传与加工-并发")
    @PostMapping("/handlefileSource_thread")
    public R handlefileSourceThread(
        @RequestParam("file") MultipartFile file,
        @RequestParam("courseFileId") Long courseFileId,
        @RequestParam("courseId") Long courseid,
        @RequestParam("sortOrder") Integer sortOrder
    ) {
        // 调用 FileUploadService 处理文件上传任务
        if (file.isEmpty()) {
            log.error("课程：" + courseid + "上传的" + courseFileId + "文件为空");
            return R.error("课程：" + courseid + "上传的" + courseFileId + "文件为空");
        }
        return fileSourceHandleThreadService.uploadFileTask(file, courseFileId, courseid,
            sortOrder);
    }

    //音视频
    @MethodLog
    @PostMapping("/uploadWebSource")
    public R uploadWebSource(@RequestBody UploadWebSourceDTO uploadWebSourceDTO) {
        try {
            //雪花算法生成新的web_id
            SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);

            StudyCourseFile studyCourseFile = studyCourseFileMapper.selectById(
                uploadWebSourceDTO.getCourseFileId());
            if (studyCourseFile == null) {
                return R.error("文件夹ID无效");
            }
//            String filePath = studyCourseFile.getFilePath();

            StudyWebSourse webSourse = new StudyWebSourse();
            webSourse.setWebId(idGenerator.nextId());
            webSourse.setWebName(uploadWebSourceDTO.getWebName());
            webSourse.setFileId(uploadWebSourceDTO.getCourseFileId());
            webSourse.setWeb(uploadWebSourceDTO.getWeb());
            webSourse.setCourseId(uploadWebSourceDTO.getCourseId());
            webSourse.setUploadedAt(new Date());
            studyWebSourseService.save(webSourse);

            if (uploadWebSourceDTO.getSortOrder() == null) {
                return R.error("排序顺序不能为空");
            }
            // 创建 sort 表数据
            StudyResourceSort resourceSort = new StudyResourceSort();
            resourceSort.setSortId(idGenerator.nextId());  // 生成 sortId
            resourceSort.setFileId(uploadWebSourceDTO.getCourseFileId());
            resourceSort.setResourceId(webSourse.getWebId());  // courseSourceId
            resourceSort.setResourceType("web");
            resourceSort.setSortOrder(uploadWebSourceDTO.getSortOrder() + 1);  // 将传入的 sortOrder 加 1

            // 插入 sort 表
            boolean sortInsertSuccess = studyResourceSortMapper.insert(resourceSort) > 0;

            return R.ok("上传网页成功" + uploadWebSourceDTO.getWebName());
        } catch (Exception e) {
            return R.error("上传网页资源失败" + e);
        }
    }

    @MethodLog("检查是否可以上传新资源")
    @GetMapping("/status")
    public R checkRateLimiterStatus() {
        try {
            // 获取限流器状态
            Map<String, Boolean> rateLimiterStatus = fileSourceHandleThreadService.checkRateLimiterStatus();

            // 检查是否有不可用的限流器
            List<String> unavailableLimiters = new ArrayList<>();
            for (Map.Entry<String, Boolean> entry : rateLimiterStatus.entrySet()) {
                if (!entry.getValue()) {
                    unavailableLimiters.add(entry.getKey());
                }
            }

            // 如果有不可用的限流器，返回 R.error
            if (!unavailableLimiters.isEmpty()) {
                String errorMessage = "以下限流器不可用: " + String.join(", ", unavailableLimiters);
                return R.error(errorMessage, rateLimiterStatus);
            }

            // 如果所有限流器都可用，返回 R.ok
            return R.ok("所有限流器均可用", rateLimiterStatus);
        } catch (Exception e) {
            return R.error("限流器状态获取失败", e.getMessage());
        }
    }


}
